package zj.xinxin.web.controller.security;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import zj.xinxin.api.moudle.security.api.ConsumerService;
import zj.xinxin.api.moudle.security.api.RoleService;
import zj.xinxin.api.moudle.security.dto.ConsumerInfoDto;
import zj.xinxin.api.moudle.security.dto.RoleDto;
import zj.xinxin.api.moudle.security.vo.UserInfoVo;
import zj.xinxin.api.moudle.utils.ConsumerUtil;
import zj.xinxin.common.annotation.Log;
import zj.xinxin.common.constant.LogConst;
import zj.xinxin.common.enums.RoleLevelEnum;
import zj.xinxin.common.result.ResponseResult;
import zj.xinxin.common.utils.BeanCopyUtil;

import javax.validation.Valid;
import java.util.*;
import java.util.function.Function;

/**
 * @author junzhou
 * @date 2022/3/23 16:26
 * @since 1.8
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户信息")
public class ConsumerController {

    @Autowired
    ConsumerService consumerService;

    @Autowired
    RoleService roleService;

    /**
     * 获取当前用户信息
     *
     * @return {@link ConsumerInfoDto} 当前用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("/getUserInfo")
    public ResponseResult<ConsumerInfoDto> getUserInfo() {
        ConsumerInfoDto consumerInfo = BeanCopyUtil.copyObject(ConsumerUtil.getUserDetails(), ConsumerInfoDto.class);

        List<RoleDto> roleList = consumerInfo.getRoleList();

        Integer roleId = RoleLevelEnum.DEFAULT.getRoleCode();
        // 如果为空则进行设置
        if (CollectionUtils.isEmpty(roleList)) {
            RoleDto consumerRole = roleService.getConsumerRole();
            consumerInfo.setRoleList(Collections.singletonList(consumerRole));
        }else {
            roleId = roleList.stream()
                    .map(RoleDto::getRoleId)
                    .min(Comparator.comparing(Function.identity()))
                    .orElse(0);
        }

        consumerInfo.setConsumerLevel(RoleLevelEnum.getGenderNameByCode(roleId));
        return ResponseResult.success("用户信息获取成功！", consumerInfo);
    }

    @ApiOperation(value = "注册用户信息")
    @Log(logType = LogConst.LOG_TYPE_REGISTER)
    @PostMapping("/register")
    public ResponseResult<Boolean> register(@RequestBody @Valid UserInfoVo registerVO) {

        if (!StringUtils.equals(registerVO.getPassword(), registerVO.getConfirmPwd())) {
            return ResponseResult.fail("两次密码不一致", Boolean.FALSE);
        }
        registerVO.setRoleId(RoleLevelEnum.CONSUMER.getRoleCode());
        Boolean isSuccess = consumerService.addUser(registerVO);
        System.out.println("接收到的注册信息为：" + registerVO);
        return ResponseResult.success(isSuccess);
    }
}
